package com.fmblzf.library.edit;

import android.content.Context;
import android.graphics.Rect;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.fmblzf.library.inter.Listener;

/**
 * Created by Administrator on 2015/11/12.
 */
public class EditTextOnlyNumber extends EditText {

    private String text="";//初始文本

    private Context mContext;//上下文

    public void setNext(EditTextOnlyNumber next) {
        this.next = next;
    }

    private EditTextOnlyNumber next ;//焦点切换的下一个控件

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    private Listener listener ;//监听事件

    public EditTextOnlyNumber(Context context) {
        this(context, null, 0);
    }

    public EditTextOnlyNumber(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EditTextOnlyNumber(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initWidget();
    }

    /**
     * 初始化控件
     */
    private void initWidget() {

        this.setText("");

        this.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

        this.setFocusableInTouchMode(true);

        this.setSelection(getText().length());

        this.addTextChangedListener(new EditTextWatcherListener());

    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        this.setSelection(getText().length());
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    /**
     * 监听文本信息变化
     */
    private class EditTextWatcherListener implements TextWatcher{

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            text = charSequence.toString();
            Log.e("",charSequence.toString());
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            Log.e("",charSequence.toString());
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length()>1){
                setText(text);
            }else if(editable.length() == 1){
                changedFocus();
            }
            Log.e("",editable.toString());
        }
    }

    /**
     * 焦点下移
     */
    private void changedFocus(){
        if (next != null){
            this.clearFocus();
            next.requestFocus();
        }
        if (listener != null){
//            this.clearFocus();
            listener.action(this.getId(), this);
        }
    }
}
